package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.enumeration.OperationType;
import com.sky.holder.EmployeeHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @program: sky-take-out
 * @description:
 * @author: 酷炫焦少
 * @create: 2024-11-15 16:44
 **/
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {}

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("公共字段填充中");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill annotation = method.getAnnotation(AutoFill.class);
        OperationType value = annotation.value();

        Object[] args = joinPoint.getArgs();
        if (Objects.isNull(args) || args.length == 0) {
            return;
        }

        LocalDateTime currentTime = LocalDateTime.now();
        Long currentUser = EmployeeHolder.get();

        Object arg = args[0];
        Class<?> aClass = arg.getClass();
        try {
            if (value == OperationType.INSERT) {
                Method setCreateTime = aClass.getDeclaredMethod("setCreateTime", LocalDateTime.class);
                Method setUpdateTime = aClass.getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                Method setCreateUser = aClass.getDeclaredMethod("setCreateUser", Long.class);
                Method setUpdateUser = aClass.getDeclaredMethod("setUpdateUser", Long.class);
                setCreateTime.invoke(arg, currentTime);
                setUpdateTime.invoke(arg, currentTime);
                setCreateUser.invoke(arg, currentUser);
                setUpdateUser.invoke(arg, currentUser);
            } else if (value == OperationType.UPDATE){
                Method setUpdateTime = aClass.getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                Method setUpdateUser = aClass.getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateTime.invoke(arg, currentTime);
                setUpdateUser.invoke(arg, currentUser);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
